package com.ruoyi.gateway.filter;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.utils.ServletUtils;
import com.ruoyi.gateway.service.ValidateCodeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 验证码过滤器
 *
 * @author weimingzhong
 */
@Component
public class SsoFilter extends AbstractGatewayFilterFactory<Object> {

    private final static String SSO_LOGIN_URL = "/sso/login";
    private static final String CODE = "code";
    private static final String UUID = "uuid";

    @Autowired
    private ValidateCodeService validateCodeService;


    @Override
    public GatewayFilter apply(Object config) {
        return (exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            //统一系统登录校验验证码
            if (StringUtils.equals(request.getURI().getPath(), SSO_LOGIN_URL)) {
                try {
                    String rspStr = resolveBodyFromRequest(request);
                    JSONObject obj = JSONObject.parseObject(rspStr);
                    validateCodeService.checkCaptcha(obj.getString(CODE), obj.getString(UUID));
                    return chain.filter(exchange);
                } catch (Exception e) {
                    return ServletUtils.webFluxResponseWriter(exchange.getResponse(), e.getMessage());
                }
            }
            return chain.filter(exchange);
        };
    }

    private String resolveBodyFromRequest(ServerHttpRequest serverHttpRequest) {
        // 获取请求体
        Flux<DataBuffer> body = serverHttpRequest.getBody();
        AtomicReference<String> bodyRef = new AtomicReference<>();
        body.subscribe(buffer -> {
            CharBuffer charBuffer = StandardCharsets.UTF_8.decode(buffer.asByteBuffer());
            DataBufferUtils.release(buffer);
            bodyRef.set(charBuffer.toString());
        });
        return bodyRef.get();
    }
}
